<template>
  <div class="data-table-container">
    <!-- 表格工具栏 -->
    <div v-if="$slots.toolbar" class="mb-4">
      <slot name="toolbar"></slot>
    </div>

    <!-- 表格容器 -->
    <div class="overflow-hidden rounded-[0.6rem] border border-gray-200" style="background-color: #FAF9F5; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);">
      <!-- 加载状态 -->
      <div v-if="loading" class="flex items-center justify-center py-12">
        <div class="loading-spinner mr-2"></div>
        <span class="text-gray-500">加载中...</span>
      </div>

      <!-- 表格内容 -->
      <div v-else class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200 border-collapse">
          <!-- 表头 -->
          <thead style="background-color: #F5F5F0;">
            <tr>
              <!-- 选择列 -->
              <th v-if="selectable" class="w-12 px-6 py-3 text-center border-r border-gray-200">
                <div class="flex items-center justify-center">
                  <input
                    type="checkbox"
                    :checked="isAllSelected"
                    :indeterminate="isIndeterminate"
                    @change="toggleSelectAll"
                    class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500 focus:ring-2 focus:ring-offset-0"
                  >
                </div>
              </th>
              
              <!-- 数据列 -->
              <th 
                v-for="column in columns" 
                :key="column.key"
                :style="column.width ? { width: column.width } : {}"
                :class="[
                  'px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider border-r border-gray-200 last:border-r-0',
                  column.align === 'center' ? 'text-center' : '',
                  column.align === 'right' ? 'text-right' : '',
                  column.sortable ? 'cursor-pointer hover:bg-gray-100 transition-colors duration-200' : ''
                ]"
                @click="column.sortable ? handleSort(column.key) : null"
              >
                <div :class="[
                  'flex items-center',
                  column.align === 'center' ? 'justify-center' : '',
                  column.align === 'right' ? 'justify-end' : ''
                ]">
                  <span>{{ column.title }}</span>
                  <div v-if="column.sortable" class="ml-2 flex flex-col">
                    <i 
                      :class="[
                        'icon-[heroicons--chevron-up] w-3 h-3',
                        sortKey === column.key && sortOrder === 'asc' 
                          ? 'text-blue-600' 
                          : 'text-gray-400'
                      ]"
                    ></i>
                    <i 
                      :class="[
                        'icon-[heroicons--chevron-down] w-3 h-3 -mt-1',
                        sortKey === column.key && sortOrder === 'desc' 
                          ? 'text-blue-600' 
                          : 'text-gray-400'
                      ]"
                    ></i>
                  </div>
                </div>
              </th>
              

            </tr>
          </thead>
          
          <!-- 表体 -->
          <tbody class="divide-y divide-gray-200" style="background-color: #FAF9F5;">
            <tr v-for="(row, index) in sortedData" :key="getRowKey(row, index)" class="hover:bg-gray-50 transition-colors duration-200 border-b border-gray-100">
              <!-- 选择列 -->
              <td v-if="selectable" class="px-6 py-4 whitespace-nowrap text-center border-r border-gray-100">
                <div class="flex items-center justify-center">
                  <input
                    type="checkbox"
                    :checked="selectedRows.includes(getRowKey(row, index))"
                    @change="toggleRowSelection(row, index)"
                    class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500 focus:ring-2 focus:ring-offset-0"
                  >
                </div>
              </td>
              
              <!-- 数据列 -->
              <td 
                v-for="column in columns" 
                :key="column.key"
                :class="[
                  'px-6 py-4 whitespace-nowrap text-sm text-gray-900 border-r border-gray-100 last:border-r-0',
                  column.align === 'center' ? 'text-center' : '',
                  column.align === 'right' ? 'text-right' : ''
                ]"
              >
                <!-- 自定义渲染 -->
                <slot 
                  v-if="column.slot" 
                  :name="column.slot" 
                  :row="row" 
                  :value="getNestedValue(row, column.key)"
                  :index="index"
                >
                  {{ getNestedValue(row, column.key) }}
                </slot>
                
                <!-- 默认渲染 -->
                <span v-else>
                  {{ formatValue(getNestedValue(row, column.key), column) }}
                </span>
              </td>
              

            </tr>
          </tbody>
        </table>
        
        <!-- 空状态 -->
        <div v-if="!data.length" class="flex flex-col items-center justify-center py-12">
          <i class="icon-[heroicons--document-text] w-12 h-12 text-gray-400 mb-4"></i>
          <p class="text-gray-500">{{ emptyText }}</p>
        </div>
      </div>
    </div>

    <!-- 分页器 -->
    <div v-if="pagination && !loading" class="mt-6 px-6 py-4 bg-gray-50 border-t border-gray-200">
      <div class="flex flex-col sm:flex-row items-center justify-between space-y-3 sm:space-y-0">
        <div class="text-sm text-gray-700 order-2 sm:order-1">
          显示第 <span class="font-medium text-gray-900">{{ (pagination.current - 1) * pagination.pageSize + 1 }}</span> 到 
          <span class="font-medium text-gray-900">{{ Math.min(pagination.current * pagination.pageSize, pagination.total) }}</span> 条，
          共 <span class="font-medium text-gray-900">{{ pagination.total }}</span> 条记录
        </div>
        
        <div class="flex items-center space-x-2 order-1 sm:order-2">
          <button
            :disabled="pagination.current <= 1"
            @click="handlePageChange(pagination.current - 1)"
            class="inline-flex items-center justify-center rounded-lg px-3 py-2 text-sm font-medium transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed border border-gray-300 bg-white text-gray-700 hover:bg-gray-50 focus:ring-gray-500"
          >
            <i class="icon-[heroicons--chevron-left] w-4 h-4 mr-1"></i>
            上一页
          </button>
          
          <div class="flex items-center space-x-1">
            <button
              v-for="page in visiblePages"
              :key="page"
              :class="[
                'inline-flex items-center justify-center rounded-lg px-3 py-2 text-sm font-medium transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed min-w-[40px]',
                page === pagination.current ? 'bg-blue-500 text-white hover:bg-blue-600 focus:ring-blue-500 shadow-sm' : 'border border-gray-300 bg-white text-gray-700 hover:bg-gray-50 focus:ring-gray-500'
              ]"
              @click="handlePageChange(page)"
            >
              {{ page }}
            </button>
          </div>
          
          <button
            :disabled="pagination.current >= totalPages"
            @click="handlePageChange(pagination.current + 1)"
            class="inline-flex items-center justify-center rounded-lg px-3 py-2 text-sm font-medium transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed border border-gray-300 bg-white text-gray-700 hover:bg-gray-50 focus:ring-gray-500"
          >
            下一页
            <i class="icon-[heroicons--chevron-right] w-4 h-4 ml-1"></i>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, defineProps, defineEmits } from 'vue'

// 定义属性
const props = defineProps({
  // 表格数据
  data: {
    type: Array,
    default: () => []
  },
  // 列配置
  columns: {
    type: Array,
    default: () => []
  },
  // 是否可选择
  selectable: {
    type: Boolean,
    default: false
  },
  // 行键字段
  rowKey: {
    type: String,
    default: 'id'
  },
  // 加载状态
  loading: {
    type: Boolean,
    default: false
  },
  // 空状态文本
  emptyText: {
    type: String,
    default: '暂无数据'
  },
  // 分页配置
  pagination: {
    type: Object,
    default: null
  }
})

// 定义事件
const emit = defineEmits([
  'sort-change',
  'selection-change', 
  'page-change'
])

// 响应式数据
const selectedRows = ref([])
const sortKey = ref('')
const sortOrder = ref('') // 'asc' | 'desc'

// 计算属性
const totalPages = computed(() => {
  if (!props.pagination) return 0
  return Math.ceil(props.pagination.total / props.pagination.pageSize)
})

const visiblePages = computed(() => {
  if (!props.pagination) return []
  const current = props.pagination.current
  const total = totalPages.value
  const pages = []
  
  let start = Math.max(1, current - 2)
  let end = Math.min(total, current + 2)
  
  for (let i = start; i <= end; i++) {
    pages.push(i)
  }
  
  return pages
})

const isAllSelected = computed(() => {
  return props.data.length > 0 && selectedRows.value.length === props.data.length
})

const isIndeterminate = computed(() => {
  return selectedRows.value.length > 0 && selectedRows.value.length < props.data.length
})

const sortedData = computed(() => {
  if (!sortKey.value || !sortOrder.value) {
    return props.data
  }
  
  return [...props.data].sort((a, b) => {
    const aVal = getNestedValue(a, sortKey.value)
    const bVal = getNestedValue(b, sortKey.value)
    
    if (aVal === bVal) return 0
    
    const result = aVal > bVal ? 1 : -1
    return sortOrder.value === 'asc' ? result : -result
  })
})

// 方法
const getRowKey = (row, index) => {
  return row[props.rowKey] || index
}

const getNestedValue = (obj, path) => {
  return path.split('.').reduce((current, key) => current?.[key], obj)
}

const formatValue = (value, column) => {
  if (column.formatter && typeof column.formatter === 'function') {
    return column.formatter(value)
  }
  return value
}

const handleSort = (key) => {
  if (sortKey.value === key) {
    sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc'
  } else {
    sortKey.value = key
    sortOrder.value = 'asc'
  }
  
  emit('sort-change', {
    key: sortKey.value,
    order: sortOrder.value
  })
}

const toggleSelectAll = () => {
  if (isAllSelected.value) {
    selectedRows.value = []
  } else {
    selectedRows.value = props.data.map((row, index) => getRowKey(row, index))
  }
  emitSelectionChange()
}

const toggleRowSelection = (row, index) => {
  const key = getRowKey(row, index)
  const selectedIndex = selectedRows.value.indexOf(key)
  
  if (selectedIndex > -1) {
    selectedRows.value.splice(selectedIndex, 1)
  } else {
    selectedRows.value.push(key)
  }
  
  emitSelectionChange()
}

const emitSelectionChange = () => {
  const selectedData = props.data.filter((row, index) => {
    return selectedRows.value.includes(getRowKey(row, index))
  })
  
  emit('selection-change', {
    selectedRows: selectedRows.value,
    selectedData
  })
}

const handlePageChange = (page) => {
  if (page < 1 || page > totalPages.value) return
  
  emit('page-change', {
    current: page,
    pageSize: props.pagination.pageSize
  })
}

// 监听数据变化，清空选择
watch(() => props.data, () => {
  selectedRows.value = []
}, { deep: true })
</script>

<style scoped>
/* 组件特定样式 */
.data-table-container {
  @apply w-full;
}

/* 修复复选框样式 */
input[type="checkbox"]:indeterminate {
  background-image: url("data:image/svg+xml,%3csvg viewBox='0 0 16 16' fill='white' xmlns='http://www.w3.org/2000/svg'%3e%3cpath d='M4 8h8'/%3e%3c/svg%3e");
}
</style>